package demo_JUC.PandC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 期望，执行顺序保持A->B->C
 */
public class demoCondition {
    public static void main(String[] args) {
        DataCondition data = new DataCondition();
        new Thread(()->{for (int i = 1; i < 50 ; i++){data.printA();}}, "A").start();
        new Thread(()->{for (int i = 1; i < 50 ; i++){data.printB();}}, "B").start();
        new Thread(()->{for (int i = 1; i < 50 ; i++){data.printC();}}, "C").start();
    }
}

class DataCondition{
    private int number = 1; // 让数组1-》2-》3

    private Lock lock = new ReentrantLock();
    // 不同监视器监视不同的方法，但是使用同样的锁lock
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();
    public void printA(){
        lock.lock(); // 加锁
        try {
            // 业务代码
            while (number != 1){
                // 等待
                conditionA.await();
            }
            number = 2;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            conditionB.signal();// A执行，精准唤醒B
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock(); // 加锁
        try {
            // 业务代码
            while (number != 2){
                // 等待
                conditionB.await();
            }
            number = 3;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            conditionC.signal();// A执行，精准唤醒B
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock(); // 加锁
        try {
            // 业务代码
            while (number != 3){
                // 等待
                conditionC.await();
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            conditionA.signal();// A执行，精准唤醒B
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
